﻿$(function () {
    layui.use(['notice', 'layer', 'table', 'iziToast', 'util', 'laypage'], function () {
        var layer = layui.layer,
            table = layui.table,
            notice = Util.notice !== null && Util.notice() !== null
                ? Util.notice() : layui.notice,
            iziToast = layui.iziToast,
            util = layui.util,
            laypage = layui.laypage;
        var lodash = _,
            tableIns = null,
            //监听表格数据行按钮
            editurl = "/business/blogmanage/edit",
            editWidowConfig = {
                title: "编辑/修改",
                type: 2,
                content: "",
                fixtolayoutbody: true,
                anim: 3,
                end: function () {
                    tableIns.reload(bloglisttableconfig);
                }
            },
            currentSystemModuleId = $("#currentSystemModuleId").val();

        var EditBlog = function (btnid, blogid, iscopy) {
            editWidowConfig.content = editurl + "?moduleid=" + currentSystemModuleId + "&buttonid=" + btnid + "&blogid=" + blogid;
            if (!lodash.isNil(iscopy))
                editWidowConfig.content += "&copy=true";
            Util.OpenMainWindow(editWidowConfig);
        };
        var DeleteBlog = function (blogid, btnid, moduleid, tableRow) {
            layer.confirm("确定要进行删除操作吗？", function (confirmIndex) {
                layer.close(confirmIndex);
                iziToast.loading("删除中，请稍候...");
                let node = new Object(DeleteNodeModel);
                node.EntityId = blogid;
                node.ButtonId = btnid;
                node.ModuleId = moduleid;
                $.deleteJSON("/api/backend/business/blogmanage/delete", node, function (res) {
                    iziToast.destroy();
                    if (!httpapi.checkResponse(res)) {
                        //输入信息校验错误
                        notice.error(res.message);
                    } else {//Success
                        notice.success(res.message);
                        if (!lodash.isNil(tableRow))
                            tableRow.del(); //删除对应行（tr）的DOM结构，并更新缓存
                    }
                });
            });
        };

        table.on('tool(bloglisttable)', function (obj) {
            var data = obj.data,
                thisElem = this,
                buttonid = layui.$(thisElem).data("buttonid");
            if (obj.event === 'Edit') {
                EditBlog(buttonid, data.Id);
            } else if (obj.event === 'Copy') {
                EditBlog(buttonid, data.Id, true);
            }
            else if (obj.event === 'Delete') {
                DeleteBlog(data.Id, buttonid, currentSystemModuleId, obj); 
            } 
            else if (obj.event === 'setRecommend') {
                var index = layer.load(2, { time: 10 * 1000 });
                httpapi.fetchGet('/api/backend/business/blogmanage/setrecommend?blogid=' + data.Id).then(res => {
                    layer.close(index);
                    if (!httpapi.checkResponse(res)) {
                        //输入信息校验错误
                        notice.error(res.message);
                    }
                    else {//Success
                        //同步更新表格和缓存对应的值
                        obj.update({
                            IsRecommend: res.data
                        });
                    }
                }).catch(error => consol.error(error));
            }
        });
        //-----常规文章表格显示-----

        //DavidLee 2020/05/15 整合博客管理界面
        var vm = new Vue({
            el: '#blogmanage',
            components: {
                'SubMenu': SubMenu,
                'AMenu': antd.Menu,
                'AMenuItem': antd.Menu.Item,
                'ASpin': antd.Spin
            },
            data: {
                //文章检索显示
                displaysearchpanel: false,
                pager: null,
                keywords: "",
                blogsdata: [],
                elapsed: 0,
                total: 0,
                pagesize: bloglisttableconfig.limit,
                page: 1,
                searchUrl: "/api/backend/business/blogmanage/search",
                //栏目菜单导航栏
                columntype: $("#columntreeType").val(),
                loadingmenus: true,
                delayTime: 200,
                menuItems: []
            },
            mounted: function () {
                tableIns = table.render(bloglisttableconfig);
                this.onLoadNavMenus();
            },
            methods: {
                //博文检索方法
                searchBlog: function () {
                    if (this.keywords.trim() !== "") {
                        this.LoadSearchBlogList(this.page, this.pagesize);
                    }
                },
                LoadSearchBlogList: function (page, pagesize) {
                    var _this = this,
                        loading = layer.load(2, { time: 10 * 1000 });
                    httpapi.fetchGet(_this.searchUrl + "?s=" + _this.keywords + "&page=" + page + "&pagesize=" + pagesize).then(res => {
                        layer.close(loading);
                        if (!httpapi.checkResponse(res))
                            //输入信息校验错误
                            iziToast.error({
                                title: '消息通知',
                                message: res.message
                            });
                        else {
                            if (!$("#blogtablepanel").hasClass("layui-hide")) {
                                $("#blogtablepanel").addClass("layui-hide");
                            }
                            _this.blogsdata = res.data.Results;
                            _this.elapsed = res.data.Elapsed;
                            _this.total = res.data.Total;
                            if (_this.pager === null) {
                                _this.pager = laypage.render({
                                    elem: 'pageContainer'
                                    , count: res.data.Total
                                    , layout: ['count', 'prev', 'page', 'next']
                                    , theme: '#1E9FFF'
                                    , limit: pagesize
                                    , jump: function (obj, first) {
                                        //首次不执行
                                        if (!first)
                                            _this.LoadSearchBlogList(obj.curr, obj.limit);
                                    }
                                });
                            }
                        }
                    }).catch(error => console.error(error));
                },
                ReloadPage: function (isreloadtable) {
                    var _this = this;
                    $("#searchpanel").removeClass("layui-anim layui-anim-up");
                    $("#blogtablepanel").removeClass("layui-anim layui-anim-fadeout layui-hide");
                    _this.displaysearchpanel = false;
                    _this.blogsdata = [];
                    _this.keywords = "";
                    _this.pager = null;
                    if (!lodash.isNil(isreloadtable) && isreloadtable)
                        tableIns.reload(bloglisttableconfig);
                },
                ItemClick: function (btnId, eventName, item) {
                    var _this = this;
                    if (eventName === 'Edit') {
                        _this.ReloadPage(false);
                        EditBlog(btnId, item.Id);
                    } else if (eventName === 'Copy') {
                        _this.ReloadPage(false);
                        EditBlog(btnId, item.Id, true);
                    } else if (eventName === 'Delete') {
                        DeleteBlog(item.Id, btnId, currentSystemModuleId);
                        let itemIndex = lodash.findIndex(_this.blogsdata, ['Id', item.Id]);
                        if (itemIndex >= 0)
                            _this.blogsdata.splice(itemIndex, 1);
                    } 
                },
                //导航栏菜单方法
                onLoadNavMenus: function () {
                    const apiUrl = '/api/backend/business/columnmanage/getauthcolumntree?columntype=' + this.columntype;
                    const me = this;
                    me.loadingmenus = true;
                    httpapi.fetchGet(apiUrl).then(res => {
                        if (!httpapi.checkResponse(res))
                            //输入信息校验错误
                            notice.error(res.message);
                        else {//Success
                            me.loadingmenus = false;
                            me.menuItems = res.data;
                        }                        
                    }).catch(error => {
                        notice.error("对不起，出现未知错误，请您联系系统管理员！");
                        console.error(error);
                    });
                },
                onSelectMenuItem: function (item) {
                    if (bloglisttableconfig.url.indexOf('?') >= 0) {
                        let arr_url = bloglisttableconfig.url.split('?');
                        bloglisttableconfig.url = arr_url[0];
                    }
                    bloglisttableconfig.url += '?isauth=true&cid=' + item.key;
                    tableIns.reload(bloglisttableconfig);
                },
                //utilities
                formatTime: function (time) {
                    return util.toDateString(time, "yyyy-MM-dd HH:mm:ss");
                }
            }
        });

        //搜索文章响应
        $("#searchBlogBtn").on("click", function () {
            var $keywords = $("input[name=blogSearch]");
            if ($keywords.val() !== "") {
                $("#blogtablepanel").addClass("layui-anim layui-anim-fadeout");
                vm.displaysearchpanel = true;
                $("#searchpanel").addClass("layui-anim layui-anim-up");
                vm.keywords = $keywords.val();
                vm.searchBlog();
            }
        });

        //监听顶部按钮栏
        var PageButtonEvent = {
            Add: function (buttonid) {
                editWidowConfig.content = editurl + "?moduleid=" + currentSystemModuleId + "&buttonid=" + buttonid;
                Util.OpenMainWindow(editWidowConfig);
                if (vm.displayType !== "table")
                    vm.ReloadPage(false);
                return false;
            }
        };
        $('.pagebuttongroup .layui-btn').on('click', function (e) {
            e.preventDefault();
            var type = $(this).data('type');
            var buttonid = $(this).data("buttonid");
            PageButtonEvent[type] ? PageButtonEvent[type].call(this, buttonid) : '';
        });

    });//layui.use([
}); //$(function () {